package com.yifi.common.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;

import com.jfinal.handler.Handler;
import com.yifi.common.utils.StringUtils;
import com.yifi.common.xss.XssHttpServletRequestWrapper;

public class XssHandler extends Handler {

	 // 排除的url，使用的target.startsWith匹配的
    private String excludePattern;
     
    /**
     * 忽略列表，使用正则
     * @param exclude
     */
    public XssHandler(String excludePattern) {
        this.excludePattern = excludePattern;
    }
 
	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		
		/** csrf跨域请求伪造问题处理，验证Referer */
		String requestUrl = request.getRequestURL().toString();
		// 判断请求是否是当前的地址
		String referrer = request.getHeader("Referer");
		/*
		if (!requestUrl.endsWith("/") && !requestUrl.endsWith("/main")  && !requestUrl.endsWith("/tomain") && !requestUrl.endsWith("/logout")&& !requestUrl.endsWith("/api_")) {
			String path1 = "";
			String path2 = "";
			URL urlOne;
			try {
				urlOne = new URL(requestUrl);
				path1 = urlOne.getHost();
				urlOne = new URL(referrer);
				path2 = urlOne.getHost();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (!path1.equals(path2)) {
				nextHandler.handle("/logout", request, response, isHandled);
				return;
			}
		}
		*/
		
		/** xss 处理*/
		Pattern pattern = Pattern.compile(excludePattern);
		//带.表示非action请求，忽略（其实不太严谨，如果是伪静态，比如.html会被错误地排除）；匹配excludePattern的，忽略
        if (target.indexOf(".") == -1 && !(!StringUtils.isBlank(excludePattern) && pattern.matcher(target).find() ) ){
            request = new XssHttpServletRequestWrapper(request);
        }
        //别忘了
        next.handle(target, request, response, isHandled);
        
	}
 
}
